package com.gulimall.cart.controller;

import com.gulimall.cart.interceptor.CartInterceptor;
import com.gulimall.cart.service.CartService;
import com.gulimall.cart.vo.CartItemVo;
import com.gulimall.cart.vo.CartVo;
import com.gulimall.common.constants.RedisKeyPrefix;
import com.gulimall.common.vo.LoginInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author coder_ccy
 * @date 2022/4/2 16:29
 */

@Controller
public class CartController {


    @Resource
    private CartService cartService;


    @GetMapping("/")
    public String index(Model model){


        CartVo cart = cartService.getCart();

        model.addAttribute("cart",cart);
        return "cartList";
    }


    @GetMapping("/success.html")
    public String success(@RequestParam("skuId") long skuId, Model model){


        CartItemVo cartItemVo = cartService.getCartItemVoBySkuId(skuId);
        model.addAttribute("cartItem",cartItemVo);


        return "success";
    }


    @GetMapping("addCart")
    public String addCart(@RequestParam("skuId") long skuId, @RequestParam("num") int num, RedirectAttributes redirectAttributes){  // 存数据，传递数据

        LoginInfo loginInfo = CartInterceptor.loginInfoThreadLocal.get();
        String cartKey = RedisKeyPrefix.CART_CARTINFO.getKeyPrefix()+loginInfo.getUserKey();
        if(loginInfo.getId()!=null){  //登录
            //1. 合并购物车
            //1.1 获得离线的

            cartService.addCart(skuId,num);//添加的是登录的购物车

            List<CartItemVo> cartItemsNoLogin = cartService.getCartItemsByKey(cartKey);

            for (CartItemVo itemVo : cartItemsNoLogin) {
                cartService.addCart(itemVo.getSkuId(), itemVo.getCount());
            }


            //2. 清除离线购物车
            cartService.clearCart(cartKey);



        }else{ //未登录
            cartService.addCart(skuId,num);//添加的是登录的购物车

        }


        //model.addAttribute("cartItem",cartItemVo);



//        cartService.addCart(skuId,num);

        redirectAttributes.addAttribute("skuId",skuId);//   url?skuId=3

        return "redirect:http://cart.gulimall.com/success.html";
    }


}
